<template>
  <div>
    <el-form
      :model="baseModel"
      :rules="formRules"
      ref="formRef"
      label-width="100px"
    >
      <div class="navLine">基本信息</div>
      <div class="baseMsg">
        <el-form-item label="商品名称" prop="integralGoodName">
          <el-input
            v-model="baseModel.integralGoodName"
            style="width: 520px"
            placeholder="请输入商品名称"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="市场价">
          <el-input-number
            :min="0"
            :controls="false"
            v-model="baseModel.guidePrice"
            style="width: 520px"
            placeholder="请输入市场价"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="库存" prop="inventory">
          <el-input-number
            :min="0"
            step-strictly
            :step="1"
            :controls="false"
            v-model="baseModel.inventory"
            style="width: 520px"
            placeholder="请输入商品库存"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="积分" prop="integralPrice">
          <el-input-number
            :min="0"
            step-strictly
            :step="1"
            :controls="false"
            v-model="baseModel.integralPrice"
            style="width: 520px"
            placeholder="请输入商品积分价"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品属性">
          <el-select
            v-model="baseModel.attributeId"
            placeholder="请选择属性模板"
            style="width: 450px"
            @change="selectTemAttsList"
          >
            <el-option
              v-for="item in temAttsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button type="text" class="ml-20" @click="jumpClass(1)"
            >前往设置</el-button
          >
          <div class="valueName">
            <div class="flex between">
              <div>属性名称</div>
              <div>属性值</div>
              <div>操作</div>
            </div>
            <div
              class="valueName__noList"
              v-if="baseModel.integralGoodsAttibuteDtos.length === 0"
            >
              暂无数据~
            </div>
            <div
              class="valueName__List"
              v-for="(item, index) in baseModel.integralGoodsAttibuteDtos"
              :key="index"
              v-else
            >
              <el-input
                v-model="item.name"
                style="width: 150px"
                maxlength="10"
              ></el-input>
              <el-input
                v-model="item.value"
                style="width: 150px"
                maxlength="20"
              ></el-input>
              <div @click="delAttr(index)" style="width: 30px">删除</div>
            </div>
          </div>
        </el-form-item>
        <el-button
          type="primary"
          plain
          style="margin-left: 100px; margin-bottom: 20px"
          size="small"
          @click="addTemAtts"
          >+ 添加属性</el-button
        >
        <el-form-item label="商品主图" prop="pic">
          <div class="text-info fs-12" style="color: rgba(69, 64, 60, 0.6)">
            尺寸建议750×1000（长图模式）或750x750（正方形模式）像素以上，大小1M以下，最多6张
            (可拖拽图片调整顺序 )
          </div>
          <div class="product" style="display: flex">
            <draggable v-model="productImgList">
              <div
                v-for="(item, index) in productImgList"
                :key="index"
                style="position: relative; margin-right: 20px"
                class="product__productImg"
                draggable="true"
              >
                <el-upload
                  class="productImg__uploader product__productImg"
                  :auto-upload="false"
                  :on-change="uploadProductImg"
                  action
                  :show-file-list="false"
                >
                  <img
                    v-if="item.img"
                    :src="item.img"
                    @click="productImgIndex = index"
                    class="product__productImg"
                  />
                </el-upload>
                <div v-if="index === 0" class="productImg-text">封面图</div>
                <i
                  class="el-icon-circle-close productImg-icon"
                  v-if="item.img"
                  @click="cancelImg(item, index)"
                ></i>
              </div>
            </draggable>
            <el-upload
              class="productImg__uploader product__productImg"
              :auto-upload="false"
              :on-change="addUploadProductImg"
              action
              :show-file-list="false"
              v-if="productImgList.length < 6"
            >
              <i class="el-icon-plus product__productImg--uploader--icon"></i>
              <div class="product__productImg--uploader--add">添加图片</div>
            </el-upload>
          </div>
        </el-form-item>
      </div>
      <div class="navLine">其他信息</div>
      <el-form-item label="运费模板" prop="freightTemplateId">
        <el-select
          v-model="baseModel.freightTemplateId"
          placeholder="请选择运费模板"
          @change="selectLogModel"
        >
          <el-option
            v-for="item in logModel"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-button type="text" class="ml-20" @click="jumpClass(2)"
          >前往设置</el-button
        >
        <LogModel
          :templateId="baseModel.freightTemplateId"
          ref="logRef"
          @getModelOption="getModelOption"
        ></LogModel>
      </el-form-item>
      <el-form-item label="初始销量">
        <el-input-number
          v-model="baseModel.sales"
          style="width: 520px"
          :controls="false"
          :placeholder="0"
          :min="0"
          step-strictly
          :step="1"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="商品重量" prop="weight" v-if="isWeight">
        <el-input-number
          :min="0"
          :controls="false"
          v-model="baseModel.weight"
          style="width: 520px"
          placeholder="0"
        ></el-input-number>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch, Ref } from "vue-property-decorator";
import { upLoad } from "@/api/index";
import { getAllAttsList, getLogistics } from "@/api/good/goods";
import draggable from "vuedraggable";
import LogModel from "@/views/logistics/common/LogModel.vue";
import storage from "@/libs/storage";
import { Getter } from "vuex-class";

@Component({
  components: {
    draggable,
    LogModel,
  },
})
export default class CodeGoodBaseInfo extends Vue {

  get formModel() {
    return this.$parent.formModel;
  }

  @Watch("formModel")
  modelChange(nVal) {
    if (nVal) {
      this.baseModel = nVal;
      this.baseModel.integralGoodsAttibuteDtos = nVal.interalGoodsAttibutes;
      this.productImgList = this.getProductImgList(nVal.albumPics);
    }
  }

  @Ref()
  readonly logRef: HTMLFormElement;

  /** 配送设置内容 */
  rections = {
    autoShippingState:
      "" /** 设置新增提货点是否自动设置送货上门,0false=禁用,1true=启用 */,
    goodPointIdsPercentage: "",
  };

  weightVlidator(rule, value, callback) {
    const regs = /^\d+.?\d{0,2}$/;
    if (Number(value) === 0) {
      callback(new Error("重量不能为0"));
    }
    if (!regs.test(value)) {
      callback(new Error("重量输入有误,数字最多保留两位小数"));
    } else {
      callback();
    }
  }

  /** 基本信息验证 */
  formRules = {
    integralGoodName: [
      { required: true, message: "请输入商品名称", trigger: "blur" },
    ],
    inventory: [{ required: true, message: "请输入商品库存", trigger: "blur" }],
    integralPrice: [
      { required: true, message: "请输入商品积分价", trigger: "blur" },
    ],
    pic: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error("请上传商品主图"));
          } else {
            callback();
          }
        },
        trigger: "change",
      },
    ],
    freightTemplateId: {
      required: true,
      message: "请选择运费模板",
      trigger: "change",
    },
    weight: [
      { required: true, message: "请输入商品重量", trigger: "blur" },
      { validator: this.weightVlidator, trigger: "blur" },
    ],
  };

  @Ref()
  readonly formRef: HTMLFormElement;

  /** 当前步骤模板 */
  baseModel = this.formModel;

  /** 属性模板数组 */
  temAttsList = [];

  /** 物流模板数组 */
  logModel = [] as any;

  /** 上传商品图片 */
  productImgList = [];

  /** 上传图片下标 */
  productImgIndex = 0;

  /** 重量信息 */
  isWeight = false;

  mounted() {
    this.getTemAttsList();
    this.getLogis(); //  物流模板
    if (storage.get("baseModel")) {
      this.$parent.formModel = this.baseModel = storage.get("baseModel");
    }
    if (this.baseModel.albumPics) {
      this.productImgList = this.getProductImgList(this.baseModel.albumPics);
    }
  }


  /**
   * 获取表单数据
   */
  async getFormModel() {
    try {
      await this.validate();
    } catch (error) {
      return Promise.reject(false);
    }
  }

  /**
   * 对整个表单进行校验
   */
  validate() {
    return this.formRef.validate();
  }

  /**
   * 获取物流模板
   */
  async getLogis() {
    const res = await getLogistics({});
    res.data.unshift({
      id: "0",
      name: "商家包邮",
    });
    this.logModel = res.data;
    this.baseModel.freightTemplateId = this.baseModel.id
      ? this.baseModel.freightTemplateId
      : "0";
  }

  /**
   * 选择物流模板
   */
  selectLogModel(e) {
    this.baseModel.freightTemplateId = e;
  }

  /**
   * 获取商品属性
   */
  async getTemAttsList() {
    const { data } = await getAllAttsList({});
    this.temAttsList = data || [];
  }

  /**
   * 选择商品属性
   */
  selectTemAttsList(temAttsId: number) {
    const currenttemAtts = this.temAttsList.find(
      (item) => item.id === temAttsId,
    );
    if (currenttemAtts) {
      this.baseModel.attributeName = currenttemAtts.name;
      this.baseModel.integralGoodsAttibuteDtos =
        currenttemAtts.attributeTemplates.map((item) => {
          return {
            ...item,
            value: item.content,
          };
        });
    }
  }

  /**
   * 添加商品属性
   */
  addTemAtts() {
    const obj = {
      content: "",
      name: "",
      id: "",
      integralGoodsId: "",
      value: "",
    };
    this.baseModel.integralGoodsAttibuteDtos.push(obj);
    if (this.$route.params.id) {
      this.modelChange(this.baseModel);
    }
  }

  /**
   * 删除商品属性
   */
  delAttr(index) {
    this.baseModel.integralGoodsAttibuteDtos.splice(index, 1);
    if (this.$route.params.id) {
      this.modelChange(this.baseModel);
    }
  }

  /**
   * 前往设置商品属性
   */
  jumpClass(type) {
    let location = null;
    this.baseModel.interalGoodsAttibutes =
      this.baseModel.integralGoodsAttibuteDtos;
    storage.set("baseModel", this.baseModel);
    this.$parent.saveFlag = true;
    switch (type) {
      case 1:
        location = {
          name: "Attribute",
          query: { options: "pick" },
          params: { options: "pick" },
        };
        break;
      case 2:
        location = {
          name: "logistics",
          query: { options: "log" },
          params: { options: "log" },
        };
        break;
    }
    this.$router.push(location);
  }

  /**
   * 还原商品图片
   */
  getProductImgList(albumPics = "") {
    let imgList = [];
    if (albumPics) {
      imgList = albumPics.split(",").map((item) => {
        return { img: item };
      });
    }
    return imgList;
  }

  /**
   * @method uploadProductImg
   * @description 修改商品主图
   */
  async uploadProductImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png"];

    const isLt1M = file.size < 2 * 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 2MB!");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.productImgList[this.productImgIndex].img = res.data;
    this.baseModel.albumPics = this.productImgList
      .filter((item) => item.img !== "")
      .map((item) => item.img)
      .join(",");
    this.baseModel.pic = this.productImgList[0].img;
    this.formRef.clearValidate("pic");
  }

  /**
   * 上传图片
   */
  async addUploadProductImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png"];

    const isLt1M = file.size < 1 * 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 1MB!");
      return;
    }
    const res = await upLoad({
      file: file.raw,
    });
    this.productImgList.push({
      img: res.data,
    });
    this.baseModel.albumPics = this.productImgList
      .filter((item) => item.img !== "")
      .map((item) => item.img)
      .join(",");
    this.baseModel.pic = this.productImgList[0].img;
    this.formRef.clearValidate("pic");
  }

  /**
   * 删除以选中图片
   */
  cancelImg(item, index) {
    this.productImgList.splice(index, 1);
    if (this.productImgList.length == 0) {
      this.formModel.pic = "";
    }
  }

  /**
   * 获取模板信息
   */
  getModelOption(modelOption) {
    this.isWeight = modelOption.valuationModel === 1 ? false : true;
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/goods/index.scss";

.pageRoll {
  overflow: auto;
  overflow-x: hidden;
  height: 750px;
}

.pageRoll::-webkit-scrollbar {
  width: 0 !important;
  height: 0 !important;
}

.navLine {
  margin-top: 40px;
  margin-bottom: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  padding-left: 30px;
  font-weight: bold;
}

.spec {
  margin-left: 40px;
  margin-bottom: 20px;
  &__left {
    margin-left: 10px;
  }
}

.specitem {
  margin-left: 100px;
  &__inp {
    display: flex;
    align-items: flex-end;
    margin-top: 10px;
    &--inside {
      width: 50px;
      margin: 0px 10px;
    }
  }
}

.dialogTitle {
  display: flex;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
}

.dialog__line {
  display: flex;
  padding-left: 20px;
  padding-top: 10px;
  justify-content: flex-start;
  align-items: flex-start;
  &__fir {
    width: 100%;
    text-align: right;
    display: flex;
    align-items: center;
  }
  &__sec {
    width: 100%;
    display: flex;
    margin-top: 10px;
    &--head {
      padding: 10px;
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      background-color: #f6f6f6;
    }
    &--body {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #999;
      padding: 10px;
    }
  }
}

.add--text {
  line-height: 30px;
  cursor: pointer;
  color: #2d8cf0;
  margin-left: 90px;
  margin-top: 10px;
}

.pick--dia {
  display: flex;
  justify-content: space-between;
  padding: 10px 30px;
  background-color: #e9f3fb;
}

.pick--input {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 30px;
}

.valueName {
  margin-top: 10px;
  width: 550px;
  padding: 20px 40px;
  border: 1px solid #d7d7d7;
  &__noList {
    display: flex;
    justify-content: center;
    color: #d7d7d7;
    font-size: 15px;
    margin-left: 20px;
    margin-top: 20px;
  }
  &__List {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    div {
      color: red;
      cursor: pointer;
    }
  }
}

.product {
  margin-top: 10px;
}

.productVideo__uploader {
  display: flex;
  align-items: flex-end;
}

.productImg__uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.productImg__uploader:hover {
  border-color: #409eff;
}

.product__productImg {
  width: 100px;
  height: 100px;
  display: inline-block;
}

.product__productVideo {
  width: 260px;
  height: 120px;
  display: inline-block;
}

.product__productVideo--uploader--icon {
  font-size: 28px;
  color: #8c939d;
  width: 260px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.productImg-icon {
  position: absolute;
  right: -8px;
  top: -5px;
  font-size: 20px;
  text-align: center;
  color: #7f7f7f;
  background-color: white;
  border-radius: 50px;
}

.product__productImg--uploader--icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 80px;
  text-align: center;
}

.product__productImg--uploader--add {
  position: absolute;
  top: 55px;
  left: 20px;
  color: #7f7f7f;
}

.productImg-uploader-clear {
  position: absolute;
  right: -0.375rem;
  top: -0.375rem;
  font-size: 20px;
  cursor: pointer;
}

.productImg-text {
  position: absolute;
  right: 0;
  bottom: 0;
  font-size: 12px;
  text-align: center;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 0px 0px 6px 6px;
  color: #ffffff;
}
</style>
